//
//  YSMineViewController.m
//  YaSha-iOS
//
//  Created by 方鹏俊 on 2017/12/8.
//  Copyright © 2017年 亚厦装饰股份有限公司. All rights reserved.
//

#import "YSMineViewController.h"
#import "YSApplicationModel.h"
#import "YSPersonalInformViewController.h"    // 个人信息
#import "YSChangePasswordViewController.h"    // 修改密码
#import "YSThemeViewController.h"    // 换肤
#import "YSSettingViewController.h"    // 设置
#import "YSAboutViewController.h"    // 关于

#import "YSMineTopView.h"
#import "YSPersonalInformationModel.h"

#import "AppDelegate.h"
#import "AppDelegate+YSSetupAPP.h"
#import <WXApi.h>
#import "YSFlowTenderViewController.h"
#import "YSDepartmentModel.h"
@interface YSMineViewController ()<QMUIMoreOperationControllerDelegate, QMUINavigationControllerDelegate, QMUIImagePreviewViewDelegate>

@property (nonatomic, strong) YSMineTopView *mineTopView;
@property (nonatomic, strong) QMUIImagePreviewViewController *imagePreviewViewController;
@property (nonatomic, strong) YSPersonalInformationModel *personalInformationModel;
@property (nonatomic, strong) QMUIMoreOperationController *moreOperationController;
@property (nonatomic,strong)RLMNotificationToken *token;
@end

@implementation YSMineViewController

NSString *const mineCellIdentifier = @"Cell";

- (BOOL)shouldCustomNavigationBarTransitionIfBarHiddenable {
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 200*kHeightScale+kTopHeight, kSCREEN_WIDTH, kSCREEN_HEIGHT-200*kHeightScale-kTopHeight);
}

- (BOOL)preferredNavigationBarHidden {
    return YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate updateAPPWithAlert:NO];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [QMUITips hideAllTipsInView:self.view];
    [self.token invalidate];
}
- (void)setNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated {
    [super setNavigationItemsIsInEditMode:isInEditMode animated:animated];
}

- (QMUIMoreOperationController *)moreOperationController {
    if (!_moreOperationController) {
        _moreOperationController = [[QMUIMoreOperationController alloc] init];
        _moreOperationController.cancelButtonTitleColor = kThemeColor;
        _moreOperationController.delegate = self;
        _moreOperationController.items = @[@[[QMUIMoreOperationItemView itemViewWithImage:UIImageMake(@"微信")        title:@"微信好友" tag:0 handler:nil],
                                             [QMUIMoreOperationItemView itemViewWithImage:UIImageMake(@"Action_Moments") title:@"朋友圈" tag:1 handler:nil]]];
    }
    return _moreOperationController;
}

- (YSMineTopView *)mineTopView {
    if (!_mineTopView) {
        _mineTopView = [[YSMineTopView alloc] init];
    }
    return _mineTopView;
}

- (void)initTableView {
    [super initTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertUpdate) name:@"update" object:nil];
    self.dataSource = @[[YSDataManager getApplicationsData:@[@{@"id": @"0",
                                                               @"name": @"个人信息",
                                                               @"className": @"YSPersonalInformViewController"},
                                                             @{@"id": @"1",
                                                               @"name": @"设置",
                                                               @"className": @"YSSettingViewController"},
                                                             @{@"id": @"2",
                                                               @"name": @"分享"},
                                                             @{@"id":@"3",
                                                               @"name":@"通讯录更新"},
                                                             @{@"id": @"4",
                                                               @"name": @"无新版"}]],
                        [YSDataManager getApplicationsData:@[@{@"id": @"5",
                                                               @"name": @"退出登录"}]]];
    [self.view addSubview:self.mineTopView];
    [self doNetworking];
}

- (void)doNetworking {
    NSString *url = [NSString stringWithFormat:@"%@%@/%@", YSDomain, getPersonInfo, [YSUtility getUID]];
    [YSNetManager ys_request_GETWithUrlString:url isNeedCache:NO parameters:nil successBlock:^(id response) {
        DLog(@"获取个人信息:%@", response);
        _personalInformationModel = [YSPersonalInformationModel yy_modelWithDictionary:response[@"data"]];
        [self.mineTopView setModel:_personalInformationModel];
        [_mineTopView.avatarButton addTarget:self action:@selector(handleImageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    } failureBlock:^(NSError *error) {
        DLog(@"error:%@", error);
    } progress:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *rowArray = [self.dataSource objectAtIndex:section];
    return rowArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mineCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mineCellIdentifier];
    }
    
    cell.accessoryType = indexPath.section == 0 ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UILabel *lineLabel = [[UILabel alloc] init];
    lineLabel.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.00];
    [cell addSubview:lineLabel];
    [lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(cell);
        make.height.mas_equalTo(1);
    }];
    
    NSArray *rowArray = [self.dataSource objectAtIndex:indexPath.section];
    YSApplicationModel *model = [rowArray objectAtIndex:indexPath.row];
    cell.textLabel.text = model.name;
    if (indexPath.section == 1) {
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor redColor];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *rowArray = [self.dataSource objectAtIndex:indexPath.section];
    YSApplicationModel *model = [rowArray objectAtIndex:indexPath.row];
    NSInteger index = [model.id integerValue];
    switch (index) {
        case 2:
        {
            [self.moreOperationController showFromBottom];
           
        }
             break;
        case 3:
        {
            RLMResults *results = [YSDepartmentModel allObjects];
            //数据库开始写入时回调一次，写入完成时回调一次,改动时也会调用一次
            YSWeak;
            self.token = [results addNotificationBlock:^(RLMResults<YSDepartmentModel *> *results, RLMCollectionChange * _Nullable change, NSError * _Nullable error) {
                YSStrong;
                if (!change || error || ![results count]) {
                    return ;
                }
                [QMUITips hideAllTipsInView:strongSelf.view];
               [QMUITips showSucceed:@"更新成功" inView:strongSelf.view hideAfterDelay:1.5];
                [weakSelf.token invalidate];
                
            }];
            [QMUITips showLoadingInView:self.view];
            //更新通讯录 删除以前的
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate saveContactWithAll:YES];
        }
             break;
        case 4:
        {
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate updateAPPWithAlert:YES];
            break;
        }
        case 5:
        {
            [self logout];
            break;
        }
        default:
        {
            Class someClass = NSClassFromString(model.className);
            UIViewController *viewController = [[someClass alloc] init];
            [self.navigationController pushViewController:viewController animated:YES];
            break;
        }
    }
}

#pragma mark - QMUIMoreOperationDelegate

- (void)moreOperationController:(QMUIMoreOperationController *)moreOperationController didSelectItemView:(QMUIMoreOperationItemView *)itemView {
    [self itemAction:itemView.tag];
}

- (void)itemAction:(int)index {
    if ([WXApi isWXAppInstalled]) {
        SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
        sendReq.bText = NO;
        //0 = 好友列表 1 = 朋友圈 2 = 收藏
        sendReq.scene = index;
        
        WXMediaMessage *mediaMessage = [WXMediaMessage message];
        mediaMessage.title = @"亚厦门户";
        mediaMessage.description = @"移动办公好帮手";
        [mediaMessage setThumbImage:[UIImage imageNamed:@"亚厦门户logo"]];
        
        WXWebpageObject *webpageObject = [WXWebpageObject object];
        webpageObject.webpageUrl = YSDownloadDomain;
        
        mediaMessage.mediaObject = webpageObject;
        sendReq.message = mediaMessage;
        
        [WXApi sendReq:sendReq];
    } else {
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
        }];
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"去下载" style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
            NSURL *wechatUrl = [NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/id414478124?mt=8"];
            [[UIApplication sharedApplication] openURL:wechatUrl];
        }];
        
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"提示" message:@"您的手机未安装微信，无法分享" preferredStyle:QMUIAlertControllerStyleAlert];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController showWithAnimated:YES];
    }
    [_moreOperationController hideToBottom];
}

#pragma mark - logout

- (void)logout {
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定" style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [YSUtility logout];
        [delegate setLoginControllerWithAlert:NO];
    }];
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"提示" message:@"是否退出登录" preferredStyle:QMUIAlertControllerStyleAlert];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController showWithAnimated:YES];
}

- (void)alertUpdate {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.text = @"发现新版本，点击更新";
    cell.textLabel.textColor = UIColorRed;
}

- (void)handleImageButtonEvent:(UIButton *)button {
    if (!self.imagePreviewViewController) {
        self.imagePreviewViewController = [[QMUIImagePreviewViewController alloc] init];
        self.imagePreviewViewController.imagePreviewView.delegate = self;
        self.imagePreviewViewController.imagePreviewView.currentImageIndex = 0;
    }
    [self.imagePreviewViewController startPreviewFromRectInScreen:CGRectMake(kSCREEN_WIDTH/2.0-37*kWidthScale, 80*kHeightScale+kTopHeight, 74*kWidthScale, 74*kWidthScale) cornerRadius:self.mineTopView.avatarButton.layer.cornerRadius];
}

#pragma mark - QMUIImagePreviewViewDelegate

- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return 1;
}

- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
    zoomImageView.image = self.mineTopView.avatarButton.imageView.image;
}

- (QMUIImagePreviewMediaType)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView assetTypeAtIndex:(NSUInteger)index {
    return QMUIImagePreviewMediaTypeImage;
}

#pragma mark - QMUIZoomImageViewDelegate

- (void)singleTouchInZoomingImageView:(QMUIZoomImageView *)zoomImageView location:(CGPoint)location {
    [self.mineTopView.avatarButton setImage:zoomImageView.image forState:UIControlStateNormal];
    [self.imagePreviewViewController endPreviewToRectInScreen:CGRectMake(kSCREEN_WIDTH/2.0-37*kWidthScale, 80*kHeightScale+kTopHeight, 74*kWidthScale, 74*kHeightScale)];
}

@end

